package com.dmall.sort.algorithm;

import java.util.Random;

/**
 * 排序辅助类
 * @author xiao1.wang
 * @date 2021/10/7 21:37
 */
@SuppressWarnings("all")
public class SortHelper {

    public static int[] generateRandomArray(int n, int rangeL, int rangeR) {
        assert rangeL <= rangeR;
        int[] arr = new int[n];
        Random random = new Random();
        for (int i = 0; i < n; i++) {
            arr[i] = random.nextInt(rangeR + 1 - rangeL) + rangeL;
        }
        return arr;
    }

    public static int[] generateNearlyOrderedArray(int n, int swapTimes) {
        int[] arr = new int[n];
        for (int i = 0; i < n; i++) {
            arr[i] = i;
        }
        Random random = new Random();
        for (int i = 0; i < swapTimes; i++) {
            int x = random.nextInt(n);
            int y = random.nextInt(n);
            swap(arr, x, y);
        }
        return arr;
    }

    public static int[] generateNearlyReverseOrderedArray(int n, int swapTimes) {
        int[] arr = new int[n];
        for (int i = 0; i < n; i++) {
            arr[i] = n - i;
        }
        Random random = new Random();
        for (int i = 0; i < swapTimes; i++) {
            int x = random.nextInt(n);
            int y = random.nextInt(n);
            swap(arr, x, y);
        }
        return arr;
    }

    private static void swap(int[] arr, int x, int y) {
        int temp = arr[x];
        arr[x] = arr[y];
        arr[y] = temp;
    }

    public static boolean isOrdered(int[] arr) {
        for (int i = 0; i < arr.length - 1; i++) {
            if (arr[i] > arr[i + 1]) {
                return false;
            }
        }
        return true;
    }

    public static void testSort(Sort sort, int[] arr) {
        long start = System.currentTimeMillis();
        sort.sort(arr);
        long end = System.currentTimeMillis();
        System.out.println(sort.getName() + ": " + (end - start) / 1000.0 + " s");
        assert isOrdered(arr);
    }
}
